package com.imist.mybatisdemo2.dao;

import com.imist.mybatisdemo2.entity.User;
import com.imist.mybatisdemo2.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDao {
    private SqlSessionFactory sqlSessionFactory ;

    private List<User> userList;

    private SqlSession getSession(){
        sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        return sqlSessionFactory.openSession();
    }
    /**
     * 查询全部用户
     * @return
     */
    public List<User> findAll(){
        SqlSession session = null;
        try {
            session = getSession();
            //userList = session.selectList("findAll");
            userList = session.selectList("queryUsers");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return userList;
    }

    /**
     * 根据ID查询单个用户
     * 这里可以给字段设置一个别名，可以被mybatis识别，不然需要参数名和SQL语句中引用的参数名一致
     * @param userId
     * @return
     */
    public User findUserById(@Param("id") Integer userId){
        SqlSession session = null;
        User user = null;
        try {
            session = getSession();
            //user = session.selectOne("findUserById",id);
            //这里使用构造器传参，防止Mybatis使用Integer.id取值出错
            user = session.selectOne("queryUsers",new User(userId));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return user;
    }

    /**
     * 新增一个用户到user表,返回一个用户
     * @param user
     * @return
     */
    public User addUser(User user){
        SqlSession session = null;
        try{
            session = getSession();
            int i = session.insert("addUser",user);
            //这里一定要记得提交不然id increment增加，但是数据不会进行插入
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        //插入之后返回一个user；其中id会被自动赋值
        return user;
    }

    /**
     * 更新用户资料
     * @param user
     * @return
     */
    public User updateUser(User user){
        SqlSession session = null;
        try{
            session = getSession();
            int i = session.update("updateUser",user);
            //这里一定要记得提交
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return user;
    }

    /**
     * 删除指定id的用户
     * @param id
     */
    public void delUser(Integer id){
        SqlSession session = null;
        try{
            session = getSession();
            session.delete("deleteUser",id);
            //这里一定要记得提交
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
    }
}
